﻿using CommunityToolkit.Mvvm.ComponentModel;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WPFDemoMVVM.ViewModel
{
    public class AnotherMainViewModel : ObservableValidator
    {
        private string? userName;

        [Required(ErrorMessage = "必填")]
        [MinLength(6, ErrorMessage = "最小长度6")]
        [MaxLength(10, ErrorMessage = "最大长度10")]
        public string? UserName
        {
            get => userName;
            set
            {
                SetProperty(ref userName, value);
            }
        }

        private int age;
        [Required(ErrorMessage = "必填")]
        [Range(18, 110, ErrorMessage = "必须在18—110")]
        public int Age
        {
            get => age;
            set
            {
                SetProperty(ref age, value);
            }
        }

        public string Error
        {
            get
            {
                var errors = new List<string>
                {
                    this[nameof(UserName)],
                    this[nameof(Age)]
                };
                return string.Join(Environment.NewLine, errors.Where(t => !string.IsNullOrEmpty(t)));
            }
        }

        public string this[string columnName]
        {
            get
            {
                switch (columnName)
                {
                    case nameof(UserName) when string.IsNullOrWhiteSpace(UserName):
                        return "必须不为空";
                    case nameof(UserName) when UserName.Length is < 6 or > 10:
                        return "必须在6和10之间";
                    case nameof(Age) when Age is < 18 or > 110:
                        return "必须在18和110之间";
                    default:
                        return string.Empty;
                }
            }
        }
    }

}
